<template>
  <div class="channelConfig">
    <h2 class="title">城市渠道配置</h2>
    <div class="teamConfigBtn">
      <Button type="primary" @click="addChannel">新增配置</Button>
      <div class="searchBox">
        <span>城市：</span>
        <div class="modalConSel">
          <Select
            v-model="selProvinceVal"
            placeholder="请选择省份"
            clearable
            filterable
            @on-change="selProvinceValChange1"
          >
            <Option
              v-for="(item, index) in provinceValList"
              :key="index"
              :value="item.cityCode"
              :label="item.cityName"
            >
            </Option>
          </Select>
          <Select
            v-model="selCityVal"
            @on-open-change="cityOpen1"
            placeholder="请选择城市"
            clearable
            filterable
            ref="resetSelect1"
          >
            <Option
              v-for="(item, index) in cityValList1"
              :key="index"
              :value="item.cityCode"
              :label="item.cityName"
            >
            </Option>
          </Select>
          <Button type="primary" class="serBtn" @click="searchBtn">查询</Button>
          <Button type="primary" @click="searchReset">重置</Button>
        </div>
      </div>
    </div>

    <div class="tab">
      <Table
        ref="TableHeight"
        :max-height="onresizeHeight"
        :columns="columns"
        :data="data"
        border
      >
      <template slot-scope="{ row }" slot="channelType">
          <span class="sp1" v-for="item in row.list">{{
            $formatter.switchName('channelType',item.channelType)
          }}</span>
        </template>
        <template slot-scope="{ row }" slot="channelName">
          <span class="sp1" v-for="item in row.list">{{
            item.channelName
          }}</span>
        </template>
        <template slot-scope="{ row }" slot="passagewayName">
          <span class="sp1" v-for="(item, index) in row.list">
            <em v-for="(items, index) in item.passageway" :key="index">
              {{ items.channelName
              }}{{ index == item.passageway.length - 1 ? "" : "," }}
            </em>
          </span>
        </template>
        <template slot-scope="{ row }" slot="operation">
          <div v-for="item in row.list" class="sp1">
            <span class="caoBtn" @click="disableChannel(item)">{{
              item.validate == 1 ? "禁用" : "启用"
            }}</span>
            <span class="caoBtn" @click="editChannel(item)">编辑</span>
          </div>
        </template>
      </Table>
    </div>

    <!-- 分页 -->
    <div class="pagePublicStyle" v-show="pageData.total > 0">
      <div class="totalCount">
        当前第 {{ pageData.current }} 页， 当前第
        {{ (pageData.current - 1) * pageData.rows + 1 }} 条到第
        {{
          pageData.current * pageData.rows > pageData.total
            ? pageData.total
            : pageData.current * pageData.rows
        }}
        条， 共 {{ pageData.total }} 条
      </div>
      <Page
        :total="pageData.total"
        :current="pageData.current"
        :page-size-opts="pageData.pageSizeOpts"
        @on-change="pageOnChangeFun"
        @on-page-size-change="pageOnPageSizeChangeFun"
        show-elevator
        show-sizer
        show-total
      />
    </div>
    <!-- 添加配置弹出框 -->
    <Modal v-model="modal" title="渠道配置" @on-cancel="modalCancel">
      <div class="modalCon">
        <span>城市：</span>
        <div class="modalConSel">
          <Select
            v-model="provinceVal"
            placeholder="请选择省份"
            clearable
            filterable
            :disabled="!create"
            @on-change="selProvinceValChange"
          >
            <Option
              v-for="(item, index) in provinceValList"
              :key="index"
              :value="item.cityCode"
              :label="item.cityName"
            >
            </Option>
          </Select>
          <Select
            v-model="cityVal"
            @on-open-change="cityOpen"
            placeholder="请选择城市"
            clearable
            filterable
            :disabled="!create"
            ref="resetSelect"
          >
            <Option
              v-for="(item, index) in cityValList"
              :key="index"
              :value="item.cityCode"
              :label="item.cityName"
            >
            </Option>
          </Select>
        </div>
      </div>
      <div class="modalCon" v-if="this.appId!=49">
        <span>渠道分类：</span>
        <div class="modalConSel">
          <Select
            v-model="channelTypeVal"
            placeholder="请选择渠道分类"
          >
            <Option
              v-for="(item, index) in channelTypeData"
              :key="index"
              :value="item.id"
              :label="item.value"
            >
            </Option>
          </Select>
        </div>
      </div>
      <div class="modalCon">
        <span>渠道名称：</span>
        <div class="modalConSel">
          <Input
            v-model="channelVal"
            style="width: 314px"
            placeholder="输入渠道名称（最多输入8个字符）"
            maxlength="8"
          />
        </div>
      </div>
      <div v-if="appId!=36">
      <div
        class="modalCon modalCon1"
        v-for="(item, index) in passagewayList"
        :key="index"
      >
        <span>通道名称：</span>
        <div class="modalConSel">
          <Input
            v-model="item.channelName"
            style="width: 314px"
            placeholder="输入通道名称（最多输入8个字符）"
            maxlength="8"
          />
          <span class="iconBox">
            <Icon
              size="20"
              class="IconAdd"
              @click="addPassageway"
              color="#2d8cf0"
              type="md-add-circle"
            />
            <em
              class="iconDisable"
              v-if="index !== 0 && !create && item.channelId"
              @click="huDisable(item)"
              >{{ item.validate == 1 ? "禁用" : "启用" }}</em
            >
            <Icon
              size="20"
              v-if="index !== 0 && !item.channelId"
              @click="passageSplice(index)"
              class="IconAdd"
              color="red"
              type="md-close-circle"
            />
          </span>
        </div>
      </div>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="modalCancel">取消</Button>
        <Button type="primary" size="large" @click="modalOk">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { Message } from "view-design";
// import cityCode from '@/common/cityCode';

import {
  getChannelList,
  getCityList,
  getChannelCreate,
  getChannelDisable,
  getChannelDisableDT,
  getChannelUpdate,
} from "@/api/configure.js";
import Button from "@/components/iview/components/button/button.vue";
import tool from "@/common/tool"
export default {
  components: { Button },
  data() {
    return {
      appId:'',

      create: false,
      userMess: JSON.parse(this.$tool.getStorage("userMess")),
      onresizeHeight: 0, //tabl高
      modal: false,
      channelId: "",

      channelVal: "",
      passagewayVal: "",

      provinceVal: "",
      cityVal: "",

      selProvinceVal: "",
      selCityVal: "",

      provinceValList: [],
      cityValList: [],
      cityValList1: [],

      passagewayList: [{ channelName: "", serialNo: 1, validate: "1" }],
      oldChannelsName: "",
      bjList: [], //老数据
      channels: [],
      newChannels: [],

      channelTypeData:[
        {
          id:1,
          value:'线下投放'
        },{
          id:2,
          value:'网络媒体'
        },{
          id:3,
          value:'渠道带看'
        },{
          id:4,
          value:'客户运营'
        }
      ],
      channelTypeVal:'',

      //分页
      pageData: {
        total: 0,
        current: 1,
        rows: 10,
        pageSizeOpts: [10, 20, 30, 40, 50],
      },

      columns: [
        {
          title: "城市",
          key: "cityName",
          width: 200,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h("span", params.row.provinceName),
              h("span", "|" + params.row.cityName),
            ]);
          },
        },
        {
          title: "渠道分类",
          key: "channelType",
          minWidth: 120,
          slot: "channelType",
          align: "center",
        },
        {
          title: "渠道名称",
          key: "channelName",
          minWidth: 120,
          slot: "channelName",
          align: "center",
        },
        {
          title: "通道名称",
          key: "passagewayName",
          minWidth: 120,
          slot: "passagewayName",
          align: "center",
        },

        {
          title: "操作",
          key: "operation",
          width: 200,
          align: "center",
          slot: "operation",
        },
      ],

      data: [],
    };
  },
  methods: {

    userType() {
      // type: 1 普通用户   2 vip用户  如果是普通用户则不能看到 couponAbleNum 这一列。
      if (this.appId==36) { //此处判断不用用户类型是否有有对应的列权限
        this.columns = this.columns.filter(col => col.key !== 'passagewayName' )
      }
      if (this.appId==49) { //此处判断不用用户类型是否有有对应的列权限
        this.columns = this.columns.filter(col => col.key !== 'channelType' )
      }
    },

    selProvinceValChange(){
     this.$refs.resetSelect.clearSingleSelect();
    },
    selProvinceValChange1(){
     this.$refs.resetSelect1.clearSingleSelect();
    },

    searchReset() {
      this.selProvinceVal = "";
      this.selCityVal = "";
      this.selProvinceVal = "";
      this.reChannelList();
    },
    searchBtn() {
      this.reChannelList();
    },

    //增加通道条数
    addPassageway() {
      let flag = this.passagewayList.some((item) => !item.channelName);
      console.log(6666, flag);
      if (flag) return this.$Message.error("请填写完成再添加");
      this.passagewayList.push({ channelName: "", validate: "1", serialNo: 1 });
    },

    //渠道列表
    reChannelList() {
      let params = {
        page: this.pageData.current,
        rows: this.pageData.rows,
        // cityCode: this.selCityVal,
        // provinceCode:this.selProvinceVal
      };
      if (this.selCityVal) {
        params.cityCode = this.selCityVal;
      }
      if (this.selProvinceVal) {
        params.provinceCode = this.selProvinceVal;
      }
      getChannelList(params)
        .then((res) => {
          console.log("渠道列表", res);
          this.data = res.list;
          this.pageData.total = parseInt(res.total);
        })
        .catch((err) => {
          console.log("cath");
          this.$Message.error(err);
        });
    },

    modalCancel() {
      this.modal = false;
      this.channelVal = "";
      this.cityVal = "";
      this.provinceVal = "";
      this.channelTypeVal = '';
      this.passagewayList = [{ channelName: "", validate: "1", serialNo: 1 }];
      this.channels = [];
      this.newChannels = [];
      // this.reChannelList();
    },

    modalOk() {
      console.log(this.channelVal, "this.channelVal");
      if (this.create) {
        console.log("我是新增");
        this.reChannelCreate();
      } else {
        console.log("我是编辑");
        this.reChannelUpdate();
      }
    },

    passageSplice(index) {
      this.passagewayList.splice(index, 1);
    },

    
    //新增渠道
    reChannelCreate() {
      console.log(this.cityVal, this.provinceVal, "aaaaaaaaaaa");
      let cFlag = this.passagewayList.some((item) => {
        return item.channelName == "";
      });
      let bFlag = "";
      for (let i = 0; i < this.passagewayList.length - 1; i++) {
        for (let j = i + 1; j < this.passagewayList.length; j++) {
          if (
            this.passagewayList[i].channelName ===
            this.passagewayList[j].channelName
          ) {
            bFlag = true;
          } else {
            bFlag = false;
          }
        }
      }
      if (!this.provinceVal) {
        this.$Message.warning("请选择省份。");
      } else if (!this.cityVal) {
        this.$Message.warning("请选择城市。");
      } else if (this.appId != 49 && !this.channelTypeVal) {
        this.$Message.warning("请选择渠道分类。");
      }else if (!this.channelVal) {
        this.$Message.warning("请输入渠道。");
      } else if (cFlag&&this.appId!=36) {
        this.$Message.warning("请输入互动方式。");
      } else if (bFlag&&this.appId!=36) {
        this.$Message.warning("互动方式不能重复。");
      } else {
        let params = {
          channelName: this.channelVal, //渠道名称
          provinceCode: this.provinceVal,
          cityCode: this.cityVal, //城市code
          channelType:this.channelTypeVal,
          serialNo: 1, //顺序号暂时不需要
          createrId: this.userMess.userId, //创建人

          
        };
        if(this.appId!=36){
          params.channels=this.passagewayList//通道
        }
        getChannelCreate(params)
          .then((res) => {
            console.log("渠道新增res1");
            this.$Message.success("渠道新增成功。");
            this.reChannelList();
            this.modalCancel();
          })
          .catch((err) => {
            console.log("catch1111");
            this.$Message.error(err);
          });
      }
    },
    huDisable(val) {
      console.log(val, "hu");
      val.validate == "1" ? (val.validate = "2") : (val.validate = "1");
      console.log(val, "hu1");
    },

    //编辑按钮
    editChannel(val) {
      this.create = false;
      this.modal = true;
      console.log(val, "bainji");
      this.provinceVal = val.provinceCode;
      this.cityVal = val.cityCode;
      this.channelVal = val.channelName;
      this.oldChannelsName = val.channelName;
      this.passagewayList = val.passageway;
      this.channelId = val.channelId;

      console.log("3333333333312333333++++++++++",this.appId);
      this.channelTypeVal = this.appId == 49 ? '' : Number(val.channelType) 

      this.bjList = JSON.parse(JSON.stringify(val.passageway));

      let params = {
        level: 3,
        parentCode: val.provinceCode,
        rows:100
      };
      getCityList(params)
        .then((res) => {
          console.log("城市open", res);
          this.cityValList = res.list;
        })
        .catch((err) => {
          this.$Message.error(err);
        });
    },
    isObjEqual(obj1, obj2) {
      var o1 = obj1 instanceof Object;
      var o2 = obj2 instanceof Object;
      if (!o1 || !o2) {
        /*  判断不是对象  */
        return obj1 === obj2;
      }

      if (Object.keys(obj1).length !== Object.keys(obj2).length) {
        return false;
        //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如：数组返回下表：let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
      }

      for (var attr in obj1) {
        var t1 = obj1[attr] instanceof Object;
        var t2 = obj2[attr] instanceof Object;
        if (t1 && t2) {
          return diff(obj1[attr], obj2[attr]);
        } else if (obj1[attr] !== obj2[attr]) {
          return false;
        }
      }
      return true;
    },
    //编辑渠道
    reChannelUpdate() {   
      let cFlag = this.passagewayList.some((item) => {
        return item.channelName == "";
      });

      
      
      let bFlag = "";
      for (let i = 0; i < this.passagewayList.length - 1; i++) {
        for (let j = i + 1; j < this.passagewayList.length; j++) {
          if (
            this.passagewayList[i].channelName == this.passagewayList[j].channelName
          ) {
            bFlag = true;
          } else {
            bFlag = false;
          }
        }
      }

      console.log(bFlag,this.passagewayList,'aaaaaaaaaathis.passagewayList')
  

      if (!this.channelVal) {
        this.$Message.warning("请输入渠道");
      } else if (cFlag&&this.appId!=36) {
        this.$Message.error("互动方式不能为空。");
      } else if (bFlag&&this.appId!=36) {
        this.$Message.error("互动方式不能重复。");
      } else {
        this.passagewayList.forEach((pitem) => {
          this.bjList.forEach((item) => {
            if (pitem.channelId == item.channelId) {
              console.log(item.channelId, "111", this.isObjEqual(item, pitem));
              if (!this.isObjEqual(item, pitem)) {
                console.log(item, pitem, "对比对象");
                if (item.channelName == pitem.channelName) {
                  delete pitem.channelName;
                  this.channels.push(pitem);
                } else {
                  this.channels.push(pitem);
                }
              }
            }
          });
        });

        this.passagewayList.forEach((pitem) => {
          if (!pitem.channelId) {
            this.newChannels.push(pitem);
          }
        });

        let params = {
          updaterId: this.userMess.userId, //创建人
          channelId: this.channelId,
          // channels: this.channels,
          // newChannels: this.newChannels,
          channelType:this.channelTypeVal
        };
        if (this.channelVal != this.oldChannelsName) {
          params.channelName = this.channelVal;
        }
        if(this.appId!=36){
          params.channels=this.channels;//通道
          params.newChannels=this.newChannels;
        }
        getChannelUpdate(params)
          .then((res) => {
            console.log("渠道新增res1");
            this.$Message.success("渠道更新成功。");
            this.reChannelList();
            this.modalCancel();
          })
          .catch((err) => {
            console.log("catch1111");
            this.channels = [];
            this.newChannels = [];
            this.$Message.error(err);
          });
      }
    },
    //选择省
    provinceOpen() {
      let params = {
        level: 2,
        page:1,
        rows:100
      };
      getCityList(params)
        .then((res) => {
          console.log("省份open", res);
          this.provinceValList = res.list;
        })
        .catch((err) => {
          this.$Message.error(err);
        });
    },
    //选择城市
    cityOpen(val) {
      console.log(this.provinceVal, "this.provinceVal");
      if (val == true && this.provinceVal) {
        let params = {
          level: 3,
          parentCode: this.provinceVal,
          page:1,
          rows:100
        };
        getCityList(params)
          .then((res) => {
            console.log("城市open", res);
            this.cityValList = res.list;
          })
          .catch((err) => {
            this.$Message.error(err);
          });
      }
    },
    cityOpen1(val) {
      if (val == true && this.selProvinceVal) {
        let params = {
          level: 3,
          parentCode: this.selProvinceVal,
          rows:100
        };
        getCityList(params)
          .then((res) => {
            console.log("城市open", res);
            this.cityValList1 = res.list;
          })
          .catch((err) => {
            this.$Message.error(err);
          });
      }
    },

    // 禁用按钮

    disableChannel(val) {
      console.log(val);

      if (val.validate == 1) {
        this.$Modal.confirm({
          title: "禁用",
          content: "<p>确定禁用此项渠道？</p>",
          onOk: () => {
            this.enable(val);
          },
          onCancel: () => {
            this.$Message.info("您取消了操作。");
          },
        });
      } else if (val.validate == 2) {
        this.$Modal.confirm({
          title: "启用",
          content: "<p>确定启用此项渠道？</p>",
          onOk: () => {
            this.enable(val);
          },
          onCancel: () => {
            this.$Message.info("您取消了操作。");
          },
        });
      }
    },

    //禁用启用
    enable(val) {
      let params = {
        channelId: val.channelId,
        status: val.validate == 1 ? 2 : 1,
        updaterId: this.userMess.userId,
      };
      console.log(params, "params");
      if(JSON.parse(tool.getStorage('userMess')).appId == 36){
        getChannelDisableDT(params)
        .then((res) => {
          this.reChannelList();
        })
        .catch((err) => {
          this.$Message.error(err);
        });
      }else{
        getChannelDisable(params)
        .then((res) => {
          this.reChannelList();
        })
        .catch((err) => {
          this.$Message.error(err);
        });
      }
    },

    addChannel() {
      this.modal = true;
      this.create = true;
    },
    goTeamList(val) {
      console.log(val, "111111111111");
      this.$router.push({
        path: "/configure_center/teamConfig/teamList",
        query: {
          id: val.id,
        },
      });
    },

    // 分页 页码改变事件
    pageOnChangeFun(page) {
      console.log("pageOnChangeFun", page);
      this.pageData.current = page;
      this.reChannelList();
    },
    // 分页 每页条数改变事件
    pageOnPageSizeChangeFun(page) {
      console.log("pageOnPageSizeChangeFun", page);
      this.pageData.rows = page;
      this.reChannelList();
    },
    // 初始化获取数据
    initData() {
      this.$nextTick(() => {
        this.onresizeHeight =
          window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 100;
      });
    },
  },
  computed: {},
  created() {
    this.appId = this.$tool.getStorage("appId")
    this.initData();
    this.reChannelList();
    this.provinceOpen();
    this.userType();
    console.log(this.$tool.getStorage("appId"),'appId')
  },
  activated() {},
  deactivated() {},
  mounted() {
    window.onresize = () => {
      return (() => {
        setTimeout(() => {
          this.onresizeHeight =
            window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 150;
        }, 10);
      })();
    };
  },
  watch: {
    // "$route"(to, from) {
    //   if(to.path == "######") {
    //     this.initData();
    //   }
    // }
  },
};
</script>

<style lang="scss" scoped>
.channelConfig {
  .ivu-table-cell {
    padding: 0;
  }
  .ivu-table-cell-slot {
    & > .sp1:last-child {
      border: none;
    }
  }
  .title {
    padding: 8px 14px;
  }
  .allCustomersP {
    padding: 8px 14px;
  }
  .teamConfigBtn {
    margin: 10px 0;
    padding-left: 14px;
    display: flex;
    flex-direction: row;
    button {
      margin-right: 10px;
    }
  }
  .tab {
    margin: 10px 0;
    
    .sp1 {
      display: block;
      min-height: 48px;
      line-height: 48px;
      text-align: center;
      border-bottom: 1px #e8eaec solid;
    }
  }
  .firstColumns {
    padding-left: 20px;
  }
  .caoBtn {
    color: #2d8cf0;
    cursor: pointer;
    display: inline-block;
    padding: 0 5px;
  }
}
.modalCon {
  display: flex;
  flex-direction: row;
  margin-top: 20px;
  & > span {
    flex: 2;
    text-align: right;
    line-height: 30px;
  }
  .modalConSel {
    flex: 9;
    display: flex;
    flex-direction: row;
    /deep/.ivu-tag-border {
      line-height: 22px;
    }
    .IconAdd[data-v-1761b028] {
      float: right;
      margin: 6px;
    }
  }
}
.searchBox {
  display: flex;
  flex-direction: row;
  & > span {
    flex: 2;
    text-align: right;
    line-height: 30px;
  }
  .modalConSel {
    flex: 9;
    display: flex;
    flex-direction: row;
    /deep/.ivu-tag-border {
      line-height: 22px;
    }
    .serBtn {
      margin-left: 10px;
    }
  }
}
/* page */
.pagePublicStyle {
 // text-align: right;
  padding: 14px 30px 14px 10px;
  // margin-right: 30px;
  display: flex;
  justify-content: space-between;
  flex-direction: row;
}
.iconBox {
  margin-top: 6px;
}
.IconAdd {
  vertical-align: -4px;
  cursor: pointer;
}
.iconDisable {
  font-size: 12px;
  color: #2d8cf0;
  margin: 0 10px;
  cursor: pointer;
}
</style>
